package com.qianbei.share.ui;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.qianbei.R;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.BaseFragmentDialog;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.Constant;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.GoldAlert;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.rxbus.RxBus;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.io.File;
import java.io.FileOutputStream;

import static com.qianbei.common.net.control.Constant.READ_TASK;

public class ShareFragmentDialog extends BaseFragmentDialog {


    private ImageView sina_share, wx_share, wxpy_share;
    public TextView share_code_save, cancel_share;

    private String mShareTitle;
    private String mShareSubTitle;
    private String mShareUrl;
    private String mShareImageUrl;
    private String mShareType;

    private boolean showimage = false;
    private ImageView mQQShare;
    private ImageView mQzongShare;
    private ProgressDialog pd;
    private boolean isShare;

    public static ShareFragmentDialog newInstance(String mShareTitle, String mShareSubTitle,
                                                  String mShareUrl, String mShareImageUrl, String type) {
        ShareFragmentDialog f = new ShareFragmentDialog();
        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putString("mShareTitle", mShareTitle);
        args.putString("mShareSubTitle", mShareSubTitle);
        args.putString("mShareUrl", mShareUrl);
        args.putString("mShareImageUrl", mShareImageUrl);
        args.putString("mShareType", type);
        f.setArguments(args);
        return f;
    }

    public static ShareFragmentDialog newInstance(String mShareTitle, String mShareSubTitle,
                                                  String mShareUrl, String mShareImageUrl, String type, boolean isShowSave) {
        ShareFragmentDialog f = new ShareFragmentDialog();
        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putString("mShareTitle", mShareTitle);
        args.putString("mShareSubTitle", mShareSubTitle);
        args.putString("mShareUrl", mShareUrl);
        args.putString("mShareImageUrl", mShareImageUrl);
        args.putString("mShareType", type);
        args.putBoolean("showimage", isShowSave);
        f.setArguments(args);
        return f;
    }


    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getArguments() != null) {
            mShareTitle = getArguments().getString("mShareTitle");// ("typ");.
            mShareSubTitle = getArguments().getString("mShareSubTitle");
            mShareUrl = getArguments().getString("mShareUrl");
            mShareImageUrl = getArguments().getString("mShareImageUrl");
            mShareType = getArguments().getString("mShareType");
            showimage = getArguments().getBoolean("showimage");
        }
        View v = View.inflate(getActivity(), R.layout.comm_share_dialog_fragment, null);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        sina_share = (ImageView) v.findViewById(R.id.sina_share);

        wx_share = (ImageView) v.findViewById(R.id.wx_share);

        wxpy_share = (ImageView) v.findViewById(R.id.wxpy_share);

        cancel_share = (TextView) v.findViewById(R.id.cancel_share);

        share_code_save = (TextView) v.findViewById(R.id.share_code_save);

        mQQShare = (ImageView) v.findViewById(R.id.qq_share);

        mQzongShare = (ImageView) v.findViewById(R.id.qzong_share);
        if (showimage) {
            share_code_save.setVisibility(View.VISIBLE);
        } else {
            share_code_save.setVisibility(View.GONE);
        }

        v.findViewById(R.id.share_view).setOnClickListener(this);
        mQzongShare.setOnClickListener(this);
        mQQShare.setOnClickListener(this);
        sina_share.setOnClickListener(this);
        wxpy_share.setOnClickListener(this);
        wx_share.setOnClickListener(this);
        cancel_share.setOnClickListener(this);
        share_code_save.setOnClickListener(this);
        return v;
    }

    public void setSinaVisibility(int visibility) {
        sina_share.setVisibility(visibility);
        wx_share.setBackgroundResource(R.drawable.roll_top_white_white45);
    }

    public ShareViewClick click;

    public interface ShareViewClick {
        public void shareClick(int viewId);
    }

    @Override
    public void onClick(View v) {
        if (click != null) {
            click.shareClick(v.getId());
        }
        dismiss();
        switch (v.getId()) {
            case R.id.qq_share:
                if (mShareType.equals("img")) {
                    shareImg(SHARE_MEDIA.QQ, mShareImageUrl, listener);
                } else if (mShareType.equals("web")) {
                    shareWeb(SHARE_MEDIA.QQ, mShareTitle, mShareSubTitle, mShareUrl, listener);
                }
                break;
            case R.id.qzong_share:
                if (mShareType.equals("img")) {
                    shareImg(SHARE_MEDIA.QZONE, mShareImageUrl, listener);
                } else if (mShareType.equals("web")) {
                    shareWeb(SHARE_MEDIA.QZONE, mShareTitle, mShareSubTitle, mShareUrl, listener);
                }
                break;
            case R.id.wxpy_share:
                if (mShareType.equals("img")) {
                    shareImg(SHARE_MEDIA.WEIXIN_CIRCLE, mShareImageUrl, listener);
                } else if (mShareType.equals("web")) {
                    shareWeb(SHARE_MEDIA.WEIXIN_CIRCLE, mShareTitle, mShareSubTitle, mShareUrl, listener);
                }
                break;
            case R.id.wx_share:
                if (mShareType.equals("img")) {
                    shareImg(SHARE_MEDIA.WEIXIN, mShareImageUrl, listener);
                } else if (mShareType.equals("web")) {
                    shareWeb(SHARE_MEDIA.WEIXIN, mShareTitle, mShareSubTitle, mShareUrl, listener);
                }
                break;
            case R.id.sina_share:


                break;
            case R.id.share_code_save:
                GetandSaveCurrentImage();
                break;


        }
    }

    /**

     */
    public void shareImg(SHARE_MEDIA shareMedia, String img, UMShareListener listener) {
        UMImage image = new UMImage(mContext, img);
        new ShareAction(mContext)
                .setPlatform(shareMedia)
                .setCallback(listener)
                .withMedia(image)
                .share();
    }

    /**
     * 分享
     *
     * @param shareMedia 分享到  朋友、朋友圈
     * @param title      分享title
     * @param subTitle   分享subtitle
     * @param url        分享url
     * @param listener   分享回调事件
     */
    public void shareWeb(SHARE_MEDIA shareMedia, String title, String subTitle, String url, UMShareListener listener) {
        UMWeb web = new UMWeb(url);
        web.setTitle(title);
        web.setDescription(subTitle);
        if (mShareImageUrl.equals("")) {
            web.setThumb(new UMImage(mContext, R.drawable.iv_logoflat));
        } else {
            web.setThumb(new UMImage(mContext, mShareImageUrl));
        }

        new ShareAction(mContext)
                .setPlatform(shareMedia)
                .setCallback(listener)
                .withMedia(web)
                .share();
    }

    private UMShareListener listener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
            pd = new ProgressDialog(mContext);
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
            pd.setCancelable(true);// 设置是否可以通过点击Back键取消
            pd.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
            pd.setMessage("准备分享");
            pd.show();
            handler.sendEmptyMessageDelayed(100, 3 * 1000);
        }

        @Override
        public void onResult(SHARE_MEDIA share_media) {
            pd.dismiss();
            new MsgAlert().show("分享成功");
            if (share_media == SHARE_MEDIA.WEIXIN_CIRCLE) {
//                new MsgAlert().show(R.string.share_success);
//                addGold(SetData.getUserID(), "6");
                if (onShareSuccess != null) {
                    isShare = true;
                    onShareSuccess.OnShareSuccess(isShare);
                }
            }
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            if (pd != null) {
                pd.dismiss();
            }
            if (share_media.equals(SHARE_MEDIA.WEIXIN) || share_media.equals(SHARE_MEDIA.WEIXIN_CIRCLE)) {
                new MsgAlert().show("目前您的微信版本过低或未安装微信，需要安装微信才能使用");
            } else if (share_media.equals(SHARE_MEDIA.QQ) || share_media.equals(SHARE_MEDIA.QZONE)) {
                new MsgAlert().show("目前您的QQ版本过低或未安装QQ，需要安装QQ才能使用");
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            pd.dismiss();
            new MsgAlert().show("分享取消");
        }
    };
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    pd.dismiss();
                    break;
            }
        }
    };


    OnShareSuccess onShareSuccess;

    public void setOnShareSuccess(OnShareSuccess onShareSuccess) {
        this.onShareSuccess = onShareSuccess;
    }

    public interface OnShareSuccess {
        boolean OnShareSuccess(boolean isShare);

    }

    /**
     * 获取和保存当前屏幕的截图
     */
    private void GetandSaveCurrentImage() {
        //1.构建Bitmap
        WindowManager windowManager = mContext.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int w = display.getWidth();
        int h = display.getHeight();

        Bitmap Bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

        //2.获取屏幕
        View decorview = mContext.getWindow().getDecorView();
        decorview.setDrawingCacheEnabled(true);
        Bmp = decorview.getDrawingCache();

        String SavePath = getSDCardPath() + "/qianbei/ScreenImage";

        //3.保存Bitmap
        try {
            File path = new File(SavePath);
            //文件
            String filepath = SavePath + "/Screen_1.png";
            File file = new File(filepath);
            if (!path.exists()) {
                path.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }

            FileOutputStream fos = null;
            fos = new FileOutputStream(file);
            if (null != fos) {
                Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();

                Toast.makeText(mContext, "截屏文件已保存至SDCard/qianbei/ScreenImage/下", Toast.LENGTH_LONG).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取SDCard的目录路径功能
     *
     * @return
     */
    private String getSDCardPath() {
        File sdcardDir = null;
        //判断SDCard是否存在
        boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        if (sdcardExist) {
            sdcardDir = Environment.getExternalStorageDirectory();
        }
        return sdcardDir.toString();
    }


    /**
     * 分享到朋友圈  增加积分
     * 增加 积分接口
     */
    public void addGold(String uid, String type) {

//        http://vnu4.top/user/addpoint/uid/31/type/1
        ServerControl sc = new ServerControl(Request.Method.GET, READ_TASK + SetData.getUserID() + "?");


        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {

                    String msg = sr.bodyData.optString("msg").toString();

                    if (!TextUtils.isEmpty(msg)) {
                        new GoldAlert().show(msg);
                        RxBus.getDefault().post("userinfo");
                    }

                }
            }

        };
        sc.startVolley();
    }
}
